package com.eastmoney.emis.edda.config;

import com.eastmoney.emis.logger.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.FileCopyUtils;

import javax.annotation.PostConstruct;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @description: Description
 * @projectName: EDDA-HSBC
 * @package: com.eastmoney.emis.edda.config
 * @author: 汪程程
 * @date: 2022/9/26 11:24 AM
 * @version: 1.0
 */
@Configuration
@ConfigurationProperties(prefix = "edda.pgp")
public class KeyHolder {
    private final Logger log = LoggerFactory.getLogger(KeyHolder.class);
    @Autowired
    private ResourceLoader resourceLoader;
    private String keyPassword;
    private String HSBC_PUBLIC_KEY = "";
    private String EMIS_PRIVATE_KEY = "";

    @PostConstruct
    public void init() throws IOException {
        HSBC_PUBLIC_KEY = new String(loadFile("hsbc.pub"));
        EMIS_PRIVATE_KEY = new String(loadFile("emis_edda.key"));
    }

    public String getKeyPassword() {
        return keyPassword;
    }

    public void setKeyPassword(String keyPassword) {
        this.keyPassword = keyPassword;
    }

    public String getHsbcPublicKey() {
        return HSBC_PUBLIC_KEY;
    }

    public String getEmisPrivateKey() {
        return EMIS_PRIVATE_KEY;
    }


    private byte[] loadFile(String fileName) throws IOException {
        // 根目录
        Resource resource = resourceLoader.getResource("file:/app/config/pgp/" + fileName);
        if (resource.exists()) {
            log.info("load key file: {} succeed", resource.getFilename());
            return FileCopyUtils.copyToByteArray(resource.getInputStream());
        }
        resource = resourceLoader.getResource("classpath:pgp_test/" + fileName);
        if (resource.exists()) {
            log.info("load key file: {} succeed", resource.getFilename());
            return FileCopyUtils.copyToByteArray(resource.getInputStream());
        }
        resource = resourceLoader.getResource("classpath:pgp/" + fileName);
        if (resource.exists()) {
            log.info("load key file: {} succeed", resource.getFilename());
            return FileCopyUtils.copyToByteArray(resource.getInputStream());
        }
        throw new FileNotFoundException("pgp key file not exist: " + fileName);
    }


}
